package cn.wolfcode.shop.cloud.mq;

import cn.wolfcode.shop.cloud.service.IOrderInfoService;
import cn.wolfcode.shop.cloud.service.ISeckillService;
import cn.wolfode.shop.cloud.domain.OrderInfo;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
@RocketMQMessageListener(
        topic = MQCounts.CREATE_ORDER,
        consumerGroup = MQCounts.ORDER_SUCCESS_DELAY_GROUP,
        selectorExpression = MQCounts.ORDER_SUCCESS_DELAY_TAG
)
public class OrderSuccessDelayMQListener implements RocketMQListener<Map> {
    @Autowired
    private IOrderInfoService orderInfoService;
    @Autowired
    private ISeckillService seckillService;
    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Override
    public void onMessage(Map map) {
        System.out.println("延时队列");
        String orderNo = (String) map.get("data");
        Long goodId = null;
        Object seckillId = map.get("seckillId");
        if(seckillId instanceof Long){
            goodId = (Long) seckillId;
        }else if(seckillId instanceof Integer){
            goodId = ((Integer)seckillId).longValue();
        }
        //查看状态是否支付，若未支付，把状态改为超时状态
        Long count = orderInfoService.changeOrderInfoStatus(orderNo,OrderInfo.STATUS_TIMEOUT);
        if(count>0){
            //回补真实库存
            seckillService.incrCount(goodId);
            //回补预库存
            seckillService.incrRedis(goodId);
            //修改本地标识
            rocketMQTemplate.syncSend(MQCounts.ORDER_BROUND_DEST,goodId);
        }
    }
}
